import React, { useContext, useEffect, useRef } from 'react';
import CacheContext from './CacheContext';
import * as cacheTypes from './cache-types';

function WithKeepAlive(props: {
  children: React.ReactNode;
  cacheId: string;
  scroll?: boolean;
}) {
  const {
    children,
    cacheId = window.location.pathname,
    scroll = false,
  } = props;
  const { mount, cacheStates, dispatch, activeCache, handleScroll } =
    useContext(CacheContext);
  const compRef = useRef<any>(null);

  // useEffect(() => {
  //   if (scroll && compRef.current) {
  //     // scroll = true, 监听缓存组件的滚动事件，调用handleScroll()缓存滚动条
  //     compRef.current.addEventListener(
  //       "scroll",
  //       (event: React.WheelEvent) => {
  //         console.log('--compRef---scroll---')
  //         handleScroll(cacheId, event)
  //       },
  //       true
  //     );
  //     () => {
  //       // 直接removeChild()
  //       // compRef.current.removeEventListener('scroll', (event: React.WheelEvent) => {
  //       //   handleRemoveScroll(cacheId, event)
  //       // })
  //     }
  //   }
  // }, [handleScroll, cacheId, compRef]);

  useEffect(() => {
    const cacheState = cacheStates[cacheId];
    if (
      cacheState &&
      cacheState.doms &&
      cacheState.status !== cacheTypes.DESTROY
    ) {
      console.log(
        '--4.widthKeepAlive--第二次加载withKeepAlive包裹的组件--组件真实dom已存在--',
      );
      // 如果真实dom已经存在，且状态不是DESTROY，则用当前的真实dom
      const doms = cacheState.doms;
      // console.log('--doms---:', doms);
      //BUG: 加载业务组件 WithKeepAlive始终只有一份，为了兼容清除已有的childNodes
      if (
        compRef.current?.childNodes &&
        compRef.current?.childNodes.length > 0
      ) {
        const existDoms = compRef.current?.childNodes;
        existDoms.forEach((dom: HTMLElement) =>
          dom?.parentNode?.removeChild(dom),
        );
      }

      doms.forEach((dom: any) => {
        compRef.current?.appendChild(dom);
        if (scroll) {
          const scrollContainer = dom.getElementsByClassName(
            'ym-add-page-container-grid',
          )[0];
          if (scrollContainer) {
            scrollContainer.addEventListener(
              'scroll',
              (event: React.WheelEvent) => {
                handleScroll(cacheId, event);
              },
              true,
            );
          }
        }
      });
      activeCache!(cacheId);
      if (scroll) {
        // 如果scroll = true, 则将缓存中的scrollTop拿出来赋值给当前dom
        doms.forEach((dom: any) => {
          if (cacheState.scrolls[dom]) {
            const scrollContainer = dom.getElementsByClassName(
              'ym-add-page-container-grid',
            )[0];
            setTimeout(() => {
              scrollContainer.scrollTop = cacheState.scrolls[scrollContainer];
            }, 0);
          }
        });
      }
    } else {
      console.log(
        '--1.widthKeepAlive--第一次加载withKeepAlive包裹的组件，执行mount--children--:',
        children,
      );
      const finalChildren = (
        Array.isArray(children)
          ? children.filter((child) => typeof child !== 'string')
          : children
      ) as any;
      // console.log('--finalChildren--:', finalChildren);
      // 如果还没产生真实dom，派发生成
      mount?.({
        cacheId,
        element: finalChildren,
        // element: React.cloneElement(finalChildren, {
        //   ...finalChildren.props,
        //   cacheWatch,
        //   removeCacheWatch
        // }),
      });
    }
  }, [cacheStates, dispatch, mount, props, handleScroll]);

  return (
    <div
      id={`keepalive_${cacheId}`}
      ref={compRef}
      style={{ height: '100%' }}
    ></div>
  );
}
export default WithKeepAlive;
